package com.qbd.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.qbd.model.Area;
import com.qbd.model.City;
import com.qbd.model.Photo;
import com.qbd.model.Product;
import com.qbd.model.Province;
import com.qbd.service.AreaService;
import com.qbd.service.CityService;
import com.qbd.service.PhotoService;
import com.qbd.service.ProductService;
import com.qbd.service.ProvinceService;
import com.qbd.utils.PageBean;
import com.qbd.utils.StringUtil;
import com.qbd.utils.UUIDUtils;

@RestController
@RequestMapping("/photo")
public class PhotoController {

	@Autowired
	private AreaService areaService;
	@Autowired
	private CityService cityService;
	@Autowired
	private ProvinceService provinceService;
	@Autowired
	private ProductService productService;
	@Autowired
	private PhotoService photoService;

	@RequestMapping("/save")
	public Map<String, Object> saveOrupdate(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request,
			HttpServletResponse response, @ModelAttribute Photo photo, String id, String cid, String pid, String aid,
			String prid) throws Exception {
		City city;
		Province province;
		Area area;
		Product product;
		// String url = upload(file, request);
		String url = null;
		photo.setPicture(url);
		if (prid.length() == 32) {
			product = productService.selectByPrimaryKey(prid);
		} else {
			province = provinceService.selectByName(pid);
			Map<String, Object> map = new HashMap<>();
			map.put("pid", province.getId());
			map.put("name", cid);
			city = cityService.selectByNameAndPid(map);
			Map<String, Object> map1 = new HashMap<>();
			map1.put("cid", city.getId());
			map1.put("name", aid);
			area = areaService.selectByNameAndCid(map1);
			Map<String, Object> map2 = new HashMap<>();
			map2.put("aid", area.getId());
			map2.put("name", prid);
			product = productService.selectByAidAndName(map2).get(0);
		}
		photo.setProduct(product);
		if (id != null) {
			photo.setId(id);
			photoService.updateByPrimaryKeySelective(photo);
		} else {
			photo.setId(UUIDUtils.getUUIDCode());
			photoService.insert(photo);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("success", "true");
		return map;
	}

	/**
	 * �ϴ��ļ���
	 * 
	 * @param file
	 * @param request
	 * @return �ϴ����������ĵ�ַ
	 * @throws Exception
	 */
	public String upload(CommonsMultipartFile file, HttpServletRequest request) throws Exception {
		String path = null;
		String ss = null;
		String ext = null;
		path = request.getServletContext().getRealPath("/upload");
		InputStream in = file.getInputStream();

		if ("".equals(file.getOriginalFilename()) || file.getOriginalFilename() == null) {
			System.out.println(file.getOriginalFilename());
			return null;
		}
		int j = file.getOriginalFilename().lastIndexOf(".");
		ext = file.getOriginalFilename().substring(j + 1);
		ss = String.valueOf(System.currentTimeMillis());
		String url = "//" + ss + "." + ext;
		OutputStream on = new FileOutputStream(new File(path, url));
		int len = 0;
		byte buffer[] = new byte[400];
		while ((len = in.read(buffer)) != -1) {
			on.write(buffer, 0, len);
		}
		in.close();
		on.close();
		return "upload" + url;
	}

	/**
	 * ɾ����¼����ɾ��������¼
	 * 
	 * @param delcaids
	 *            ɾ����id
	 * @param response
	 * @return
	 */
	@RequestMapping("/delete")
	public Map<String, Object> delete(String ids, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();
		String arry[] = ids.split(",");
		int j = 0;
		for (int i = 0; i < arry.length; i++) {
			photoService.deleteByPrimaryKey(arry[i]);
			j++;
		}
		if (j == arry.length) {
			map.put("success", "true");
			map.put("delNums", j);
		} else {
			map.put("errorMsg", "false");
		}
		return map;
	}

	/**
	 * ��ҳ��ʾ���м�¼
	 * 
	 * @param page
	 *            ҳ��
	 * @param rows
	 *            ����
	 * @param response
	 * @param omsProduct
	 *            ��Ʒ����
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public Map<String, Object> list(String page, String rows, HttpServletResponse response, @ModelAttribute Photo photo,
			String sname) throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", StringUtil.formatLike(sname));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Photo> userList = photoService.selectByPage(map);
		Long total = photoService.getTotal(map);
		map.clear();
		map.put("rows", userList);
		map.put("total", total);
		return map;
	}
}
